var createError = require('http-errors');
var cors = require('cors');
var express = require('express');
var path = require('path');
var bcrypt = require('bcryptjs');
var jwt = require('jsonwebtoken');

var Loki = require('lokijs');
var db = new Loki('user.json');
var User = db.addCollection('user');

var app = express();

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(express.static(path.join(__dirname, 'public')));

// Note: LokiJS has an alternative promisified version. Here we use
// original version (all sync operations) for simplicity.

app.post('/login', (req, res) => {

    const {mail, pass} = req.body;

    console.log('RECEIVED LOGIN', mail, pass);

    let user = User.findOne({mail});

    if (!user) {
      res.status(400).json({message: 'Incorrect Account or Password'});
      return;
    }

    const validated = bcrypt.compareSync(pass, user.pass);

    if (!validated) {
      console.log('USER PASS MISMATCH')
      res.status(400).json({ message: "Incorrect Account or Password"});
      return;
    }

    const token = jwt.sign({_id: user._id}, 'JESUS DIED FOR YOU', {expiresIn: "10d"});
    res.status(200).json({token});

})

app.post('/register', (req, res) => {

  const {mail, pass} = req.body;
  console.log('RECEIVED REGISTER', mail, pass);


  let user = User.findOne({mail});
  console.log

  if (user) {
    res.status(400).json({message: 'Existing user name'});
    return;
  }

  User.insert({mail, pass: bcrypt.hashSync(pass, bcrypt.genSaltSync(4))});

  res.status(200).json({ok: true});

})

app.use(function(req, res, next) {
  next(createError(404));
});

module.exports = app;
